﻿// HSS.Interlink.UI.InterlinkCommandT.cs
// ----------------------------------------------------------------------------
// Licensed under the MIT license (http://www.opensource.org/licenses/mit-license.html)
// ----------------------------------------------------------------------------
// HighSpeed-Solutions, LLC
// Copyright (c) 2001-2012
// ----------------------------------------------------------------------------
// File:       InterlinkCommandT.cs
// Author:     HSS\gbanta
// Created:    01/17/2012
// Modified:   01/17/2012
// ----------------------------------------------------------------------------
namespace HSS.Interlink.UI
{
	#region Using Directives
	using System;
	using System.Diagnostics;

	#endregion

	#region InterlinkCommand<T>
	/// <summary>
	/// Generic InterlinkCommand.
	/// </summary>
	/// <typeparam name="T">The parameter Type.</typeparam>
	public class InterlinkCommand<T> : IInterlinkCommand
	{
		#region Events
		/// <summary>
		/// An event handler that indicates the state of CanExecute
		/// has changed.
		/// </summary>
		public event EventHandler CanExecuteChanged;
		#endregion

		#region Fields

		readonly Action<T> _execute;
		readonly Predicate<T> _canExecute;

		#endregion

		#region Constructors
		/// <summary>
		/// Constructs a new InterlinkCommand.
		/// </summary>
		/// <param name="execute">The Action to execute.</param>
		public InterlinkCommand(Action<T> execute)
			: this(execute, null)
		{
		}
		/// <summary>
		/// Constructs a new InterlinkCommand.
		/// </summary>
		/// <param name="execute">The Action to execute.</param>
		/// <param name="canExecute">The Predicate to call.</param>
		public InterlinkCommand(Action<T> execute, Predicate<T> canExecute)
		{
			if (null == execute)
				throw new ArgumentNullException("execute");
			_execute = execute;
			_canExecute = canExecute;
		}
		#endregion

		#region Methods
		/// <summary>
		/// Fires the <see cref="CanExecuteChanged"/> events.
		/// </summary>
		public void OnCanExecuteChanged()
		{
			var handler = CanExecuteChanged;
			if (null != handler)
				handler(this, EventArgs.Empty);
		}
		/// <summary>
		/// Calls to this method determine if the command can be executed.
		/// </summary>
		/// <param name="parameter">An optional parameter.</param>
		/// <returns>True if the command can execute; otherwise false.</returns>
		[DebuggerStepThrough]
		public bool CanExecute(object parameter)
		{
			return _canExecute == null ? true : _canExecute((T)parameter);
		}
		/// <summary>
		/// Attempts to execute the requested action.
		/// </summary>
		/// <param name="parameter">The optional parameter.</param>
		public void Execute(object parameter)
		{
			if (null != _execute)
				_execute((T)parameter);
			this.OnCanExecuteChanged();
		}
		#endregion
	}
	#endregion
}
